package com.imagination.applet.domain.support.authentication.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.imagination.applet.domain.support.authentication.modal.WechatToken;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class LoginService {

    private final RestTemplate restTemplate;

    @Value(value = "${payment.wechat.appId}")
    private String appId;

    @Value(value = "${payment.wechat.appSecret}")
    private String secret;
    private final String grantType = "client_credential";

    public WechatToken auth(String code) throws JsonProcessingException {
        Map param = Maps.newHashMap();
        param.put("appId", appId);
        param.put("secret", secret);
        param.put("grantType", grantType);
        param.put("jsCode", code);
        String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appId={appId}&secret={secret}&js_code={jsCode}&grant_type={grantType}", String.class, param);
        return new ObjectMapper().readValue(result, WechatToken.class);
    }


}
